import { formatTime } from '../../utils/util'
Page({
    data: {
        orderInfo: null, //订单信息
        orderGoods: null, //前端生成的订单商品列表信息
        weightTotal: 0, //预估重量
        active: 0, //选择的方式
        shipp_active: 0, //选择的运输方式
        pickPointInfo: null, //提货点信息
        message: '', //留言
        agreement: false, //同意协议
        totalPrice: 0, //总金额
        buttonLoading: false,
        payMoney: 0, //后端获取的支付金额
        order_id: '', //预支付订单ID
        demand: [], //选择的特殊需求
        tips: '达不到起订数、或该区域不在发货范围',
    },
    onLoad: function(options) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', ({ data }) => {
            //计算合计金额
            let totalPrice = (Number(data.orderInfo.total_price) + Number(data.orderInfo.pack_amount)).toFixed(2)
            if (data.orderInfo.freight_list.length > 0) {
                totalPrice = (Number(totalPrice) + Number(data.orderInfo.freight_list[0].freight)).toFixed(2)
            } else {
                wx.showModal({
                    content: this.data.tips,
                    confirmColor: '#188075',
                    showCancel: false
                })
            }
            this.setData({ orderInfo: data.orderInfo, orderGoods: data.orderGoods, weightTotal: data.weightTotal, totalPrice })
        })
    },
    //切换方式
    onMethodsChange({ currentTarget }) {
        const { index } = currentTarget.dataset
        if (index === 0) { //邮寄
            this.setData({ active: index })
            this.computedTotalPrice()
        } else { //自提
            if (this.data.pickPointInfo) {
                this.setData({ active: index })
                this.computedTotalPrice()
            } else {
                //获取提货点信息
                this.request({
                    url: '/api/index/config?type=3',
                    loadingTip: '加载中'
                }, res => {
                    this.setData({ pickPointInfo: res.data, active: index })
                    this.computedTotalPrice()
                })
            }
        }
    },
    //重新计算总价格
    computedTotalPrice() {
        const { active, shipp_active, orderInfo } = this.data
        let totalPrice = 0
        if (active === 0) { //邮寄
            totalPrice = (Number(orderInfo.total_price) + Number(orderInfo.pack_amount)).toFixed(2)
            if (orderInfo.freight_list.length > 0) {
                totalPrice = (Number(totalPrice) + Number(orderInfo.freight_list[shipp_active].freight)).toFixed(2)
            }
        } else {
            totalPrice = orderInfo.total_price
        }
        this.setData({ totalPrice })
    },
    //切换邮寄方式
    onShippChange({ currentTarget }) {
        const index = currentTarget.dataset.index
        let totalPrice = (Number(this.data.orderInfo.amount) + Number(this.data.orderInfo.pack_amount) + Number(this.data.orderInfo.freight_list[index].freight)).toFixed(2)
        this.setData({ shipp_active: index, totalPrice })
    },
    //点击导航
    openLocation() {
        const { lat, lng, house, addr } = this.data.pickPointInfo
        wx.openLocation({
            latitude: Number(lat),
            longitude: Number(lng),
            scale: 14,
            name: house,
            address: addr
        })
    },
    //前往选择收货地址
    toChooseAddress() {
        const { m_addr } = this.data.orderInfo
        wx.navigateTo({
            url: '/pages/address_manage/index?choose=true',
            events: {
                setAddressInfo: ({ data }) => {
                    // if (m_addr && data.addr_id === m_addr.addr_id) return
                    //重新根据收货地址获取订单判断区域是否支持配送
                    this.request({
                        url: `/api/cart/cart?addr_id=${data.addr_id}`,
                        loadingTip: '处理中'
                    }, ({ data }) => {
                        if (data.freight_list.length === 0) {
                            return wx.showModal({
                                content: this.data.tips,
                                confirmColor: '#188075',
                                showCancel: false,
                                // success: (res) => {
                                //     if (res.confirm) {
                                //         this.toChooseAddress()
                                //     }
                                // }
                            })
                        }
                        //计算合计金额
                        let totalPrice = (Number(data.total_price) + Number(data.freight_list[this.data.shipp_active].freight)).toFixed(2)
                        this.setData({
                            orderInfo: data,
                            totalPrice
                        })
                    }, () => {
                        this.setData({
                            ['orderInfo.m_addr']: null
                        })
                    })
                }
            }
        })
    },
    //协议
    onAgreeChange({ detail }) {
        this.setData({ agreement: detail })
    },
    //查看订单商品详情
    toFlowerDetail() {
        const { orderInfo, orderGoods, shipp_active, active, totalPrice } = this.data
        wx.navigateTo({
            url: '/pages/settlement_flower/index',
            success: res => {
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    data: {
                        orderInfo,
                        orderGoods,
                        shipp_active,
                        active,
                        totalPrice
                    }
                })
            }
        })
    },
    //前往特殊需求
    toDemand() {
        wx.navigateTo({
            url: '/pages/settlement_demand/index',
            success: res => {
                res.eventChannel.emit('acceptDataFromOpenerPage', { data: this.data.demand })
            },
            events: {
                setDemand: ({ data }) => {
                    this.setData({ demand: data })
                }
            }
        })
    },
    /**点击立即支付（验证） */
    async verification() {
        const { active, agreement, orderInfo } = this.data
        if (active === 0) {
            if (!orderInfo.m_addr) return wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            })
        }
        if (this.data.orderInfo.freight_list.length === 0 && this.data.active === 0) {
            return wx.showToast({
                title: this.data.tips,
                icon: 'none'
            })
        }

        if (!agreement) return wx.showToast({
            title: '请阅读并同意交易规则',
            icon: 'none'
        })

        this.setData({ buttonLoading: true })
        this.getPayInfo()
    },
    /**获取订单预支付 */
    getPayInfo() {
        const { active, orderInfo, shipp_active, message, order_id, demand } = this.data
        if (order_id) return this.pay()
        let reqData = {
            pei_type: active === 1 ? 0 : orderInfo.freight_list[shipp_active].shipping_type
        }

        if (active === 0) reqData.addr_id = orderInfo.m_addr.addr_id
        if (message) reqData.intro = message
        if (demand.length > 0) {
            reqData.extra = []
            demand.forEach(item => {
                reqData.extra.push({
                    title: item,
                    content: item
                })
            })
        }
        this.request({
            url: '/api/cart/handle',
            method: 'POST',
            data: reqData
        }, res => {
            this.setData({ payMoney: res.data.total_price, order_id: res.data.order_id })
            this.pay()
        }, null, () => {
            this.setData({ buttonLoading: false })
        })
    },
    /**立即支付 */
    pay() {
        this.setData({ payLoading: true })
        getApp().globalData.cartCheckNum = 0 //此时购物车选中的商品已经清空
        this.request({
            url: '/api/payment/order',
            method: 'POST',
            data: {
                code: 'wxpay',
                order_id: this.data.order_id
            }
        }, ({ data }) => {
            wx.requestPayment({
                timeStamp: data.pay_data.timeStamp,
                nonceStr: data.pay_data.nonceStr,
                package: data.pay_data.package,
                signType: data.pay_data.signType,
                paySign: data.pay_data.paySign,
                success: () => {
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        mask: true
                    })
                    this.delay(() => {
                        wx.redirectTo({
                            url: '/pages/order/index?active=1'
                        })
                    })
                },
                fail: () => {
                    this.payFail()
                }
            })
        }, () => {
            this.payFail()
        })
    },
    payFail() {
        wx.showToast({
            title: '支付失败',
            icon: 'error'
        })
        this.delay(() => {
            wx.redirectTo({
                url: '/pages/order/index?active=0'
            })
        })
    },
    /**拨打电话 */
    tel() {
        wx.makePhoneCall({
            phoneNumber: this.data.pickPointInfo.mobile
        })
    }
})